<!DOCTYPE html>
<html>
<head>
    <title>WebSocket 测试页面</title>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <style>
        .message-container {
            height: 300px;
            border: 1px solid #ccc;
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 10px;
        }
        .input-container {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="message-container" id="messageContainer"></div>
    
    <div class="input-container">
        <input type="text" id="messageInput" placeholder="请输入消息">
        <button onclick="sendMessage()">发送</button>
    </div>
    
    <button onclick="connect()">连接 WebSocket</button>
    <button onclick="disconnect()">断开连接</button>

    <script>
        let stompClient = null;
        
        function connect() {
            const socket = new SockJS('http://192.168.5.243:19001/ws-endpoint');
            stompClient = Stomp.over(socket);
            
            const headers = {
                'Content-Type': 'application/json'
            };
            
            stompClient.connect(headers, function(frame) {
                console.log('连接成功: ' + frame);
                showMessage('系统消息：连接成功');
                
                // 订阅消息
                stompClient.subscribe('/topic/messages', function(response) {
                    const message = JSON.parse(response.body);
                    showMessage('收到消息: ' + message.content);
                });
            }, function(error) {
                console.log('连接错误: ' + error);
                showMessage('系统消息：连接失败');
                // 添加重连逻辑
                setTimeout(connect, 5000);
            });
        }
        
        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
                showMessage('系统消息：已断开连接');
            }
            console.log("已断开连接");
        }
        
        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value;
            
            if (stompClient && message) {
                const chatMessage = {
                    content: message
                };
                stompClient.send("/app/chat", {}, JSON.stringify(chatMessage));
                messageInput.value = '';
            }
        }
        
        function showMessage(message) {
            const messageContainer = document.getElementById('messageContainer');
            const messageElement = document.createElement('div');
            messageElement.textContent = message;
            messageContainer.appendChild(messageElement);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
    </script>
</body>
</html> 